package com.example.springmvcdemo;

import org.springframework.http.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.net.URI;
import java.net.URISyntaxException;

@RestController
public class ResponseEntityDemo {

    // 使用构造函数方式
    @RequestMapping("/demo1")
    public ResponseEntity<String> demo1() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("Custom-Header", "Value");
        headers.setContentType(MediaType.APPLICATION_JSON);

        return new ResponseEntity<>(
                "响应内容",  // 响应体
                headers,    // 响应头
                HttpStatus.OK // 状态码
        );
    }

    // 使用静态方法方式
    @RequestMapping("/demo2")
    public ResponseEntity<String> demo2() {
        return ResponseEntity
                .status(HttpStatus.CREATED) // 设置状态码为201
                .header("Custom-Header", "Value1", "Value2") // 添加响应头
                .header("Another-Header", "Value")
                .body("响应内容"); // 设置响应体
    }

    // 使用便捷静态工厂方法
    @RequestMapping("/demo3")
    public ResponseEntity<String> demo3() throws URISyntaxException {
        // 创建新资源的URI
        URI location = new URI("/new-resource/123");

        // 返回201 Created响应，包含Location头部
        return ResponseEntity.created(location).body("资源已创建");
    }

    // 处理不同类型的内容
    @RequestMapping("/demo4")
    public ResponseEntity<Object> demo4() {
        // 返回JSON数据
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_JSON)
                .body("{\"message\":\"Hello\", \"status\":\"success\"}");
    }

    // 返回HTML内容
    @RequestMapping("/demo5")
    public ResponseEntity<String> demo5() {
        String htmlContent = "<html><body><h1>Hello HTML</h1></body></html>";

        return ResponseEntity.ok()
                .contentType(MediaType.TEXT_HTML)
                .body(htmlContent);
    }
}